<?php 
class Mysql{
	private $conn;
	function __construct($houstname,$username,$password,$dbname,$charset='utf8'){
		$this->conn=@mysql_connect($houstname,$username,$password);
		if (!$this->conn) {
			$this->errorMsg('MYSQL连接失败','http://www.baidu.com');exit;
		}
		mysql_select_db($dbname);
		mysql_set_charset($charset);
	}
	function errorMsg($msg,$url){
		echo "<script>alert('$msg');";
		if ($url) {
			echo "window.location.href='$url'";
		}else{
			echo "window.history.go(-1);";
		}
		echo "</script>";
	}
	/**
	 * [getOne 获取单条数据]
	 * @param  [string] $sql [sql语句]
	 * @return [array]      [返回一维数组]
	 */
	function getOne($sql){

		$result = mysql_query($sql);
		$data = array();
		if($result && mysql_num_rows($result)>0){
			$data = mysql_fetch_assoc($result);
		}
		return $data;
	}
	/**
	 * [getAll 获取所有信息]
	 * @param  [string] $sql [sql语句]
	 * @return [array]      [返回二维数组]
	 */
	function getAll($sql){
		$result = mysql_query($sql);
		$data = array();
		if($result && mysql_num_rows($result)>0){
			while($row = mysql_fetch_assoc($result)){
				$data[] = $row;
			}
		}
		return $data;
	}
	/**
	 * [insert 插入数据]
	 * @param  [string] $table [表名]
	 * @param  [array] $data  [数据]
	 * @return [type]        [成功返回添加ID，失败返回FALSE]
	 */
	function insert($table,$data){
		$str = '';
		$str .="INSERT INTO `$table` ";
		$str .="(`".implode("`,`",array_keys($data))."`) "; 
		$str .=" VALUES ";
		$str .= "('".implode("','",$data)."')";
		// echo $str;
		
		$res = mysql_query($str);
		if($res && mysql_affected_rows()>0){
			return mysql_insert_id();
		}else{
			return false;
		}
	}
	/**
	 * [update 更新数据库]
	 * @param  [string] $table [表名]
	 * @param  [array] $data  [更新的数据]
	 * @param  [string] $where [条件]
	 * @return [type]        [更新成功返回影响的行数，更新失败返回false]
	 */
	function update($table,$data,$where){
		$sql = 'UPDATE '.$table.' SET ';
		foreach($data as $key => $value){
			$sql .= "`{$key}`='{$value}',";
		}
		$sql = rtrim($sql,',');
		$sql .= " WHERE $where";
		$res = mysql_query($sql);
		if($res && mysql_affected_rows()){
			return mysql_affected_rows();
		}else{
			return false;
		}
	}
	/**
	 * [delete 删除数据]
	 * @param  [string] $table [表名]
	 * @param  [string] $where [条件]
	 * @return [type]        [成功返回影响的行数，失败返回false]
	 */
	function delete($table,$where){
		$sql = "DELETE FROM `{$table}` WHERE {$where}";
		$res = mysql_query($sql);
		if($res && mysql_affected_rows()){
			return mysql_affected_rows();
		}else{
			return false;
		}
	}
}






 ?>